var express = require('express') //引入express框架
var mysql = require('mysql') //引入mysql
var bodyParser = require('body-parser'); //引入处理数据
const { json } = require('body-parser');
var app = express(); //实例化
app.use(bodyParser.json()); //实例化接收参数json
app.use(bodyParser.urlencoded({extended:false})); //实例化接收formdata
var dbConfig = {
    host:'127.0.0.1',
    user:'root',
    password:'llf0202062',
    database:'test'
}
//连接数据库配置

function handleError(err) {
    if (err) {
        // 如果是连接异常，自动重新连接
        console.log('err code:' + err.code);
        if (err.code === 'PROTOCOL_CONNECTION_LOST' || err.code === 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR' || err.code === 'ETIMEDOUT') {
            connectFunc();
        } else {
            console.error(err.stack || err);
        }
    }
}

function connectFunc() {
    connect = mysql.createConnection(dbConfig);
    connect.connect(handleError);
    connect.on('error', handleError);
}
var connect ;

connectFunc();



app.listen('8889',()=>{ //设置node服务端口 启动服务
    console.log('服务启动成功','http://localhost:8889');
})
app.all('*', function(req, res, next) {
    // res.header("Access-Control-Allow-Origin", "http://localhost:8889");
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    next();
  });

app.get('/getData',(req,res)=>{ //登录方法 GET
    var sql = 'SELECT * FROM users'; //查询用
    connect.query(sql,(err,result)=>{
        if(err){
            console.log('[SELECT ERROR] - ',err.message);
            return;
          }
        res.json({code:0,data:result,msg:'请求成功'});
    })
    
})

// 登录
app.get('/login',(req,res)=>{ //登录方法
    var sql = 'SELECT * FROM users WHERE username = ?' //查询账号是否存在user表中
    console.log(req.query.username);
    let username = req.query.username; //接收请求参数
    let password = req.query.password;
    if(!username){
        return res.json({code:202,msg:'账号不得为空'});
    }
    if(!password){
        return res.json({code:202,msg:'密码不得为空'});
    }
    connect.query(sql,req.query.username,(err,result)=>{ //执行sql
        if(result.length>0){ //查询数据结果
            if(result[0].username == username && result[0].password == password){ //匹配结果
                return res.json({code:0,msg:'登陆成功',data:result[0]});
            }else{
                return res.json({code:201,msg:'账号或密码错误'});
            }
            
        }else{
            return res.json({code:203,msg:'账号不存在'}); //没查到数据
        }
    })
})

//注册get userid设为主键自增
app.get('/reg',(req,res)=>{
    let sql = 'INSERT INTO users(username,password) VALUES(?,?)'
    let username = req.query.username;
    let password = req.query.password;
    if(!username){
        return res.json({code:402,msg:'账号不得为空'});
    }
    if(!password){
        return res.json({code:402,msg:'密码不得为空'});
    }

    let c = 'SELECT * FROM users WHERE username=?'
    connect.query(c,username,(err,result)=>{
        if(err){
            console.log('[SELECT ERROR] - ',err.message);
            return;
        }
        if(result.length>0){
            return res.json({code:401,msg:'账号已存在'});
        }else{
            let data = [username,password]
            connect.query(sql,data,(errs,results)=>{
                if(errs){
                    console.log('[INSERT ERROR] - ',errs.message);
                    return;
                }    
                if(results.insertId>0){
                    return res.json({code:0,msg:'注册成功',data:results});
                }else{
                    return res.json({code:500,msg:'系统错误'});
                }
            })
        }
    })
    
})

const WebSocket = require('ws');
const ws = new WebSocket.Server({ port: 3001 });
let parseData = require('./parseData');
let localConfig = require('./localConfig');
let clients = [];
let users = [];

ws.on('connection', function (client) {
    client.id=users.length;
    clients.push(client);
    client.on('message', function (msg) {
        // console.log('msg>>>',msg);
        let _respData = parseData.respData(msg);
        // console.log('_respData>>>',_respData);
        switch(_respData.mid){
            case localConfig.ProtoList.ChatMsg:
                {
                    let data = _respData.deMessage;
                    if(data.type == 'add'){
                        if(users.length<clients.length){
                            users.push(data.curuser);
                        }
                        data.users = {
                            curuser:data.curuser,
                            users:users
                        };
                    }
                    let sendmsg = parseData.reqData('Msg.ChatMsg',localConfig.ProtoList.ChatMsg,data);
                    for(let i=0;i<clients.length;i++){
                        let client = clients[i];
                        client.send(sendmsg);
                    }
                }
                break;
            default:
                console.warn('协议号未定义',mid);
                break
        }
        
    });

    client.on('close', () => {
        let index = clients.indexOf(client);
        if (index !== -1) {
            let data = {};
            data.type = 'leave';
            data.msg = users[index].username;
            data.curuser = users[index];
            
            clients.splice(index, 1);
            users.splice(index, 1);

            let sendmsg = parseData.reqData('Msg.ChatMsg',localConfig.ProtoList.ChatMsg,data);
            for(let i=0;i<clients.length;i++){
                let client = clients[i];
                client.send(sendmsg);
            }
            console.log('clinet closed',index,client.id);
        }
    });
});
